package fms.services.impls;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import fms.common.UserInfo;
import fms.services.ServiceException;
import fms.services.UserQueryService;
import fms.services.impls.tables.TableNameConsts;
import fms.services.impls.tables.UserTableConsts;
import fms.services.persistence.ConnectionFactory;
import fms.services.persistence.ConnectionTool;

public class UserQueryServiceImpl implements UserQueryService {

	private Logger log = Logger.getLogger(UserQueryServiceImpl.class.getName());
	
	private static String getUserByUserId_SQL = "SELECT * FROM "
		+ TableNameConsts.TABLE_USER + " WHERE " + UserTableConsts.USER_ID
		+ "=?";
	
	
	public UserInfo getUserInfoByID(String userid) throws ServiceException {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		conn = ConnectionFactory.getFactory().getConnection();
		String sql = getUserByUserId_SQL;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, userid);
			rs=ps.executeQuery();
			List<UserInfo> infos = buildUser(rs);
			if (infos.size() > 0) {
				return infos.get(0);
			}
		}
		catch (SQLException e) {
			e.printStackTrace();
			log.log(Level.SEVERE, "get user by userid failed! " + userid);
			throw new ServiceException(
					ServiceException.SERVICE_EXCUTING_EXCEPTION_DBERROR,
			"get user by userid failed!");
		} finally {
			ConnectionTool.closeConnection(conn, ps, null);
		}
		return null;
	}

	private List<UserInfo> buildUser(ResultSet rs) throws SQLException{
		ArrayList<UserInfo> al = new ArrayList<UserInfo>();
		while (rs.next()) {
			UserInfo info = new UserInfo();
			info.setUserID(rs.getString(UserTableConsts.USER_ID));
			info.setUserPass(rs.getString(UserTableConsts.USER_PASS));
			info.setUserName(rs.getString(UserTableConsts.USER_NAME));
			info.setUserDpmt(rs.getInt(UserTableConsts.USER_DPMT));
			info.setUserSex(rs.getInt(UserTableConsts.USER_SEX));
			info.setUserPhone(rs.getString(UserTableConsts.USER_PHONE));
			info.setUserAdd(rs.getString(UserTableConsts.USER_ADD));
			al.add(info);
		}
		return al;
	}

	public String getServiceName() {
		return "User Query Service Implementation";
	}

	public String getServiceVersion() {
		return "1.0";
	}
	
	public static void main(String[] args) {
		UserQueryServiceImpl uqs=new UserQueryServiceImpl();
		UserInfo user = new UserInfo();
		try {
			user = uqs.getUserInfoByID("kakarui");
		} catch (ServiceException e) {
			
			e.printStackTrace();
		}
		System.out.println(user.getUserName()+" "+ user.getUserAdd() + " " +user.getUserDpmt());
	}
}
